package cn.fengLone.pay.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.fengLone.pay.service.PayService;
import cn.fengLone.pay.util.SimpleUtil;
import cn.fengLone.pay.util.SpringUtil;



/**
 * 
 * @description 支付结果通知类
 * 
 * @compny 深圳风轮科技有限公司
 * 
 * @author Guo PengFei
 * 
 * @date 2017-11-20
 * 
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/aliPayNotify")
public class AliPayNotifyController {

	@Resource
	private PayService payService;
	
	
	/**
	 * 支付宝支付同步通知接口
	 * 
	 * 同步接口，仅校验订单的有效性，并不更改数据库的表单状态，
	 * 然后显示支付成功
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/aliPaySynPayNotify")
	public String aliPaySynPayNotify(HttpServletRequest request,
			HttpServletResponse response, Model model){
		
		Map<String, String> resultMap = new HashMap<String, String>();

		Map<String, String> paramMap = SimpleUtil.getRequestParam(request);
		try{
			resultMap = payService.aliPaySyncRes(paramMap);
		}catch(Exception e){
			e.printStackTrace();
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("system_error"));
//			return "payResult/error";
		}
		
		model.addAllAttributes(resultMap);
		String return_code = resultMap.get("return_code");
		if(return_code.equals("0"))
			return "payResult/error";
		else 
			return "payResult/success";
				
	}
	
	
	/**
	 * 支付宝支付异步通知接口
	 * 
	 * 异步接口，更新订单状态、保存订单信息，通知第三方系统
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/aliPayAsynPayNotify")
	@ResponseBody
	public String aliPayAsynPayNotify(HttpServletRequest request,
			HttpServletResponse response, Model model){
		
		Map<String, String> resultMap = new HashMap<String, String>();

		Map<String, String> paramMap = SimpleUtil.getRequestParam(request);
		try{
			resultMap = payService.aliPayAsyncRes(paramMap);
		}catch(Exception e){
			e.printStackTrace();
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("system_error"));
		}
		
		String return_code = resultMap.get("return_code");
		if(return_code.equals("0"))
			return "FAIL";
		else 
			return "SUCCESS";
	}
}
